#include <os/safety.h>
#include <os/task.h>
#include <os/schedule.h>
#include <arch/page.h>
#include <lib/string.h>
#include <lib/type.h>

int SafetyCheckRange(void *src, uint64_t bytes)
{
    uint64_t addr = (address_t)src;
    if (cur_task->vmm != NULL && (addr < KERNEL_VMM_BASE) && (addr + bytes < KERNEL_VMM_BASE))
        return 0;
    return -1;
}

int MemCopyFromUser(void *des, void *src, uint64_t bytes)
{
    if (!SafetyCheckRange(src, bytes))
    {
        if (CheckPageRead(ADDR(src), bytes) < 0)
        {
            return -1;
        }
        if (src != NULL && des != NULL)
            memcpy(des, src, bytes);
        return 0;
    }
    return -1;
}

int MemCopyToUser(void *des, void *src, uint64_t bytes)
{
    if (!SafetyCheckRange(des, bytes))
    {
        if (CheckPageRead(ADDR(src), bytes) < 0)
            return -1;

        if (src != NULL && des != NULL)
            memcpy(des, src, bytes);

        return 0;
    }
    return -1;
}
